package com.wangyadong.hobby.admin.servcie.impl;

import com.wangyadong.hobby.admin.servcie.IQuestionService;
import com.wangyadong.hobby.common.constants.RedisKeyConstants;
import com.wangyadong.hobby.common.dao.MyBatisDao;
import com.wangyadong.hobby.common.question.Question;
import com.wangyadong.hobby.common.utils.UniqueIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.*;

import static com.wangyadong.hobby.common.utils.MapObjectConvert.maptoObject;
import static com.wangyadong.hobby.common.utils.MapObjectConvert.objectToMap;

@Service
public class QuestionServiceImpl implements IQuestionService {


    Jedis conn = new Jedis("127.0.0.1");


    @Override
    public int saveOrUpdateQuestion(Question question) throws Exception {
        if (!StringUtils.isBlank(question.getId())) {
            question.setId(UniqueIDUtil.getUniqueID() + "");
        }
        long now = System.nanoTime() / 1000;
        String key = RedisKeyConstants.QUESTION.getCode() + question.getId();
        conn.hmset(key, objectToMap(question));

        conn.zadd(RedisKeyConstants.SCORE.getCode(), now, key);
        conn.zadd(RedisKeyConstants.TIME.getCode(), now, key);
        return 0;
    }

    @Override
    public int deleteQuestion(Long id) {
        String key = RedisKeyConstants.QUESTION.getCode() + id;
        Map<String, String> map = conn.hgetAll(key);
        Set<String> keys = map.keySet();
        String[] strings = new String[keys.size()];
        Iterator<String> iterator = keys.iterator();
        int i = 0;
        while (iterator.hasNext()) {
            String next = iterator.next();
            strings[i] = next;
            i++;
        }
        Long result = conn.hdel(key, strings);
        conn.zrem(RedisKeyConstants.SCORE.getCode(), key);
        conn.zrem(RedisKeyConstants.TIME.getCode(), key);
        return result.intValue();
    }

    @Override
    public Question getQuestionDetail(Long id) throws InstantiationException, IllegalAccessException {
        String key = RedisKeyConstants.QUESTION.getCode() + id;
        return (Question) maptoObject(conn.hgetAll(key), Question.class);
    }

    @Override
    public List<Question> queryQuestionListByPage(int pageNum, int pageSize, Map<String, Object> map) throws InstantiationException, IllegalAccessException {
        int start = (pageNum - 1) * pageSize;
        int end = start + pageSize - 1;
        Set<String> ids = conn.zrevrange(RedisKeyConstants.QUESTION.getCode(), start, end);
        List<Question> articles = new ArrayList<>();
        for (String id : ids) {
            Map<String, String> articleData = conn.hgetAll(id);
            articleData.put("id", id);
            articles.add((Question) maptoObject(articleData, Question.class));
        }
        return articles;
    }
}
